package com.tron.sync.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tron.sync.entities.OfficeRole;
import com.tron.sync.entities.SyndaUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class PlatformToFedocServiceImpl implements PlatformToFedocService{

    @Resource
    private SyndaEmployeeService syndaEmployeeService;

    @Resource
    private OfficeRoleService officeRoleService;

    @Override
    public Map<String, Object> syncPlatformToFedoc() {
        long l = System.currentTimeMillis();
        Map<String,Object> resultMap = new HashMap<>();
        int pageNo = 0;
        int size = 300;
        int newSize= 300;
        int total = 0;
        while (newSize == size){
            IPage<SyndaUser> page = new Page<>(pageNo,size);
            IPage<SyndaUser> userIPage = syndaEmployeeService.page(page);
            List<SyndaUser> records = userIPage.getRecords();
            List<OfficeRole> officeRoles = new ArrayList<>();
            if (!records.isEmpty()){
                records.forEach(o->{
                    List<OfficeRole> roleList = officeRoleService.list(new QueryWrapper<OfficeRole>().eq("f_user_id", o.getId()));
                    if (roleList.isEmpty()){
                        //如果历史数据没有迁移后在表中还是没有查到该用户的配置,则设置默认的对自己直属部门的查询权限
                        OfficeRole newOfficeRole = new OfficeRole();
                        newOfficeRole.setUserId(o.getId());
                        newOfficeRole.setCanQuery("1"); //设置默认的查询权限
                        newOfficeRole.setCanSign("0");
                        newOfficeRole.setCanSynergy("0");
                        newOfficeRole.setCreateDate("2021-04-01 00:00:00");
                        newOfficeRole.setGroupId(o.getGroupId());
                        newOfficeRole.setGroupType("2");
                        newOfficeRole.setCreateUserId("sysadmin");
                        officeRoles.add(newOfficeRole);
                    }
                });
                total +=officeRoles.size();
                officeRoleService.saveBatch(officeRoles);
                log.info("=========当前查询第{}页================数据更新{}条",pageNo,officeRoles.size());
            }
            newSize = userIPage.getRecords().size();
            pageNo++;
        }
        long l1 = System.currentTimeMillis();
        resultMap.put("更新数据总数",total);
        resultMap.put("message","更新完成");
        resultMap.put("耗时",l1-l);
        return resultMap;
    }
}
